<template>
<!--  <h2>利用统计</h2>-->
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm"  :inline="true">
      <el-form-item label="日期">
        <el-date-picker
          v-model="daterange"
          type="daterange"
          value-format="yyyy-MM-dd"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-s-data"  @click="count">统计</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" ref="refbut">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-download"  @click="exportExcel">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-printer"  @click="print">打印</el-button>
      </el-col>
    </el-row>

    <div style="width: 70%; margin: 0 auto;">
      <table class="custom-table">
        <thead>
        <tr class="title">
          <th :colspan="2" style="border: 0 !important;">
            <h1 style="font-size: 28px;" class="h1">
              利用统计表
            </h1>
          </th>
        </tr>
        <tr>
          <th>日期</th>
          <th>借阅次数</th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="(item, index) in tableData" :key="index">
          <td>{{ item.name }}</td>
          <td>{{ item.value }}</td>
        </tr>
        </tbody>
      </table>
    </div>

    <div style="width: 70%; height: 300px; margin: 0 auto; margin-top: 3%">
      <div id="lineChart" style="width: 90%; height:100%;"></div>
    </div>
  </div>
</template>

<script>
import * as XLSX from "xlsx";
import {tongji} from "@/api/archive/statistics/utilizingStatistics/utilizingStatistics";
import * as echarts from "echarts";

export default {
  name: "index",
  data() {
    return {
      queryParams: {
        startTime: undefined,
        endTime: undefined
      },
      daterange: [],
      // 统计表格数据
      tableData: [],
    }
  },
  created() {
    this.count()
  },
  methods: {
    // 统计
    count() {
      if(this.daterange != null) {
        this.queryParams.startTime = this.daterange[0]
        this.queryParams.endTime = this.daterange[1]
      } else {
        this.queryParams.startTime = undefined
        this.queryParams.endTime = undefined
      }
      tongji(this.queryParams).then(response=>{
        this.tableData = response.data
        this.getLineChart()
      })
    },
    // 导出
    exportExcel() {
      const worksheet = XLSX.utils.table_to_sheet(document.querySelector('.custom-table'));
      const workbook = XLSX.utils.book_new();
      // 将处理后的日期数据作为日期添加到工作表中
      for (let i = 0; i < this.tableData.length; i++) {
        const item = this.tableData[i];
        const columnLetter = XLSX.utils.encode_col(0); // 获取动态列索引对应的字母表示形式
        const cellAddress = `${columnLetter}${i + 3}`; // 组合动态列索引和行索引
        console.log(columnLetter, cellAddress)
        // 处理日期，只保留年月信息
        const formattedDate = item.name.substring(0, 7); // 假设日期字符串的格式是'YYYY-MM-DD HH:mm:ss'
        // 在工作表中设置处理后的日期
        worksheet[cellAddress] = { v: formattedDate };
      }
      XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');

      console.log(worksheet)
      const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
      this.saveAsExcel(excelBuffer, `利用统计_${new Date().getTime()}`);
    },

    saveAsExcel(buffer, filename) {
      const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = `${filename}.xlsx`;
      link.click();
    },

    // 打印
    print() {
      $("input").each(function () {
        $(this).attr('value', $(this).val());
      });

      const tableElement = document.querySelector('.custom-table');
      const iframe = document.createElement('iframe');
      console.log(iframe,"---------------------------")
      iframe.style.display = 'none';
      document.body.appendChild(iframe);
      const iframeDoc = iframe.contentWindow.document;

      iframeDoc.open();
      iframeDoc.write(`
          <html>
          <head>
<!--            <title>打印表单</title>-->
            <style>
              @media print {
                .h1 {
                  font-size: 28px;
                  text-align: center;
                }

                .h3 {
                  font-size: 20px;
                  text-align: right;
                }

                .table {
                  margin-top: 5px;
                  padding: 1%;
                }
                .custom-table {
                  width: 100%; /* 设置表格宽度为100% */
                  margin: 0 auto;
                  border-collapse: collapse; /* 合并单元格边框 */
                }

                .custom-table th,
                .custom-table td {
                  padding: 8px; /* 设置单元格内边距 */
                  padding:5px 5px 5px 5px;
                  align-items:center;
                  justify-content:flex-start;
                  opacity:1;
                  color:#000000;
                  letter-spacing:2px;
                  font-family:仿宋;
                  font-size:16px;
                  border: 1px solid #000; /* 设置单元格边框样式 */
                  padding: 8px; /* 设置单元格内边距 */
                  text-align: center; /* 设置单元格文本居中 */
                }

                .title {
                  heigth: 5em;
                  line-height: 5em;
                  text-align: center;
                  padding:5px 5px 5px 5px;
                  align-items:center;
                  justify-content:center;
                  letter-spacing:4px;
                  font-weight:bold;
                  font-family:宋体;
                  font-size:24px;
                  opacity:1;
                  margin: 0 auto;
                  background:rgba(255, 255, 255, 0) !important;
                  border: 0 !important;
                  box-shadow:0 0 0 0 rgba(255, 255, 255, 0) !important;
                }
              }
            </style>
          </head>
          <body>
             ${tableElement.outerHTML}
            <script>
              window.onload = function() {
                window.print();
                window.close();
              }
            <\/script>
          </body>
          </html>
      `);
      iframeDoc.close();
    },

    // 制作折线图
    getLineChart(){
      var data = []
      var date = []
      this.tableData.forEach(item => {
        date.push(item.name);
        data.push(item.value);
      });
      this.$nextTick(() => {
        var myChart = echarts.init(document.getElementById('lineChart'));
        // 指定图表的配置项和数据
        var option = {
          color: ['#3460c7'],
          grid: {
            top: "5%",
            height: "80%",
            width: "80%"
          },
          xAxis: {
            axisTick: {
              show: false
            },
            type: 'category',
            boundaryGap: false,
            axisLine: {
              lineStyle: {
                color: '#cccccc',
              }
            },
            axisLabel: {
              textStyle: {
                color: '#666666'
              }
            },
            data: date
          },
          tooltip: {
            trigger: 'axis'
          },
          yAxis: {
            axisTick: {
              show: false
            },
            type: 'value',
            splitLine: {
              show: true,
              lineStyle: {
                type: 'dashed'
              },
            },
            axisLine: {
              lineStyle: {
                color: '#cccccc',
              }
            },
            axisLabel: {
              textStyle: {
                color: '#666666'
              }
            },

          },
          areaStyle: {
            opacity: 0.8,
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
              offset: 0,
              color: '#7a9ff0'
            }, {
              offset: 1,
              color: '#bdd8fc'
            }])
          },
          series: [{
            data: data,
            type: 'line',
            smooth: true,
            areaStyle: {}
          }]
        };
        // 使用刚指定的配置项和数据显示图表。
        myChart.setOption(option);
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.h1 {
  font-size: 28px;
  text-align: center;
}

.h3 {
  font-size: 20px;
  text-align: right;
}

.table {
  margin-top: 5px;
  padding: 1%;
}
.custom-table {
  width: 100%; /* 设置表格宽度为100% */
  margin: 0 auto;
  border-collapse: collapse; /* 合并单元格边框 */
}

.custom-table th,
.custom-table td {
  padding: 8px; /* 设置单元格内边距 */
  padding:5px 5px 5px 5px;
  align-items:center;
  justify-content:flex-start;
  opacity:1;
  color:#000000;
  letter-spacing:2px;
  font-family:仿宋;
  font-size:16px;
  border: 1px solid #000; /* 设置单元格边框样式 */
  padding: 8px; /* 设置单元格内边距 */
  text-align: center; /* 设置单元格文本居中 */
}

.title {
  heigth: 5em;
  line-height: 5em;
  text-align: center;
  padding:5px 5px 5px 5px;
  align-items:center;
  justify-content:center;
  letter-spacing:4px;
  font-weight:bold;
  font-family:宋体;
  font-size:24px;
  opacity:1;
  margin: 0 auto;
  background:rgba(255, 255, 255, 0) !important;
  border: 0 !important;
  box-shadow:0 0 0 0 rgba(255, 255, 255, 0) !important;
}
</style>
